package chapter3;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author caiya
 * @date 2020/3/18 23:05
 */
@Slf4j
public class ThreadLocalRandomTest {
    private static Random random = new Random();

    public static void main(String[] args) {
        /**
         * Random 类在多线程下虽然是线程安全的，但是会存在多个线程竞争一个CAS的问题，也就说其它等待线程会进行自旋操作，影响并发性能
         * ThreadLocalRandom 给每个线程分配独立的种子，这样就不会存在自旋操作的问题
         */
        ThreadDemo threadDemo = new ThreadDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(threadDemo).start();
        }
        ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(threadLocalDemo).start();
        }
    }

    static class ThreadDemo implements Runnable {
        @Override
        public void run() {
            log.debug("ThreadDemo 线程：{}, 随机数：{}", Thread.currentThread().getName(), random.nextInt(1000));
        }
    }

    static class ThreadLocalDemo implements Runnable {
        @Override
        public void run() {
            log.debug("ThreadLocalDemo 线程：{}, 随机数：{}", Thread.currentThread().getName(), ThreadLocalRandom.current().nextInt(1000));
        }
    }

}


